package src

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
)

type Response struct {
	Status int    `json:"status"`
	Msg    string `json: "msg"`
	Datas  any    `json:"datas"`
}

func (r *Response) ToString() string {
	return "{\n" + "	status:" + strconv.Itoa(r.Status) + ",\n	msg:" + r.Msg + ",\n	datas:" + fmt.Sprintf("%+v", r.Datas) + "\n}"
}

func NewResponse(status int) Response {
	return Response{
		Status: status,
		Msg:    GetMsg(status),
		Datas:  nil,
	}
}

func CustomResponse(status int, datas any) Response {
	return Response{
		Status: status,
		Msg:    GetMsg(status),
		Datas:  datas,
	}
}

// 构建 http 请求
func request(method string, apiUrl string, paramas map[string]string) ([]map[string]any, int) {
	var result []map[string]any
	switch method {
	case "GET":
		u, err := url.ParseRequestURI(apiUrl)
		if err != nil {
			Logger.Warn("gitcode 46 line,解析URI失败")
			return nil, ERROR
		}

		data := url.Values{}
		for key := range paramas {
			data.Set(key, paramas[key])
		}
		u.RawQuery = data.Encode()

		//fmt.Println(u.String())
		Logger.Info("请求URL：" + u.String())
		resp, err := http.Get(u.String())
		if err != nil {
			Logger.Warn("gitcode 57 line,Get 请求失败，URL：" + u.String() + "ERROR:" + err.Error())
			return nil, ERROR
		}

		defer resp.Body.Close()
		body, err := io.ReadAll(resp.Body)
		err = json.Unmarshal([]byte(string(body)), &result)
		Logger.Info("body read success")
		if err != nil {
			Logger.Warn("gitcode 65 line, body read error: " + err.Error())
			return nil, ERROR
		}
		return result, SUCCESS
	case "POST":

		data := url.Values{}

		for key := range paramas {
			data.Set(key, paramas[key])
		}

		resp, err := http.PostForm(apiUrl, data)
		if err != nil {
			return nil, ERROR
		}
		defer resp.Body.Close()
		body, err := io.ReadAll(resp.Body)

		err = json.Unmarshal([]byte(string(body)), &result)
		if err != nil {
			return nil, ERROR
		}

		return result, SUCCESS

	default:
		return nil, ERROR
	}
}

func GetReports(apiUrl string, param map[string]string) Response {
	result, err := request("GET", apiUrl, param)
	if err != SUCCESS {
		return NewResponse(ERROR)
	}
	return CustomResponse(SUCCESS, result)
}
